package io.renren.modules.api.service.impl;


import io.renren.common.exception.RRException;
import io.renren.common.utils.QmSendPush;
import io.renren.modules.api.dao.UserDao;
import io.renren.modules.api.dao.UserFrequentlyRouteDao;
import io.renren.modules.api.dao.UserFrequentlyRouteSectionDao;
import io.renren.modules.api.entity.PsCouponEntity;
import io.renren.modules.api.entity.UserCouponsEntity;
import io.renren.modules.api.entity.UserEntity;
import io.renren.modules.api.service.*;
import io.renren.modules.driver.dao.SjDriverDao;
import io.renren.modules.driver.entity.SjDriverEntity;
import io.renren.modules.psorder.dao.PsOrderDao;
import io.renren.modules.psorder.entity.PsOrderEntity;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("userService")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SjDriverDao driverDao;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private DriverTokenService driverTokenService;
	@Autowired
	private PsOrderDao psOrderDao;
	@Autowired
	private UserFrequentlyRouteDao userFrequentlyRouteDao;
	@Autowired
	private UserFrequentlyRouteSectionDao userFrequentlyRouteSectionDao;
	@Autowired
	private UserCouponsService userCouponsService;
	@Autowired
	private PsCouponService psCouponService;

	@Override
	public UserEntity queryObject(Long userId){
		UserEntity userEntity = userDao.queryObject(userId);
		return userEntity;
	}
	
	@Override
	public List<UserEntity> queryList(Map<String, Object> map){
		return userDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return userDao.queryTotal(map);
	}
	
	@Override
	public void save(String mobile, String password){
		SysUserEntity user = new SysUserEntity();
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(password, salt).toHex());
		user.setSalt(salt);
		user.setMobliephone(mobile);
		user.setUsername(mobile);
		sysUserDao.saveByDynamicCol(user);//save(user);
		/*UserEntity user = new UserEntity();
		user.setPhone(mobile);
		user.setUsername(mobile);
		user.setPassword(DigestUtils.sha256Hex(password));
		user.setCreateTime(new Date());
		userDao.save(user);*/
	}
	
	@Override
	public void update(UserEntity user){
		userDao.update(user);
	}
	
	@Override
	public void delete(Long userId){
		userDao.delete(userId);
	}
	
	@Override
	public void deleteBatch(Long[] userIds){
		userDao.deleteBatch(userIds);
	}

	@Override
	public UserEntity queryByMobile(String mobile) {
		return userDao.queryByMobile(mobile);
	}

	@Override
	public long login(String mobile, String password) {
		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("mobilephone",mobile);
//		SysUserEntity user = sysUserDao.queryUser(map);
		UserEntity user = queryByMobile(mobile);
//		Assert.isNull(user, "账号不存在");
//		//账号不存在、密码错误
//		if(user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
//			throw new RRException("账号或密码不正确");
//		}
		if( user == null ) {
//			throw new RRException("账号不存在");
			UserEntity userTemp = new UserEntity();
			userTemp.setUsername(mobile);
			userTemp.setPhone(mobile);
			userTemp.setCreateTime(new Date());
			userDao.save(userTemp);
			return userTemp.getUserId();
		}
		//账号锁定
//		if( user != null && user.getState() == 0){
//			throw new RRException("账号已被锁定,请联系管理员");
//		}
		/*//密码错误
		if(!user.getPassword().equals(DigestUtils.sha256Hex(password))){
			throw new RRException("手机号或密码错误");
		}*/

		return user.getUserId();
	}

	@Override
	public Map<String, Object> loginByNoPassWd(String mobile) {
		//先判断司机表里有没有
		SjDriverEntity driver = driverDao.queryObjectByUserName(mobile);
		if (driver == null) {	//司机表没有就查用户表的
			UserEntity user = queryByMobile(mobile);
			if (user == null) {  //如果用户表也没有就创建用户
				UserEntity userTemp = new UserEntity();
				userTemp.setUsername(mobile);
				userTemp.setPhone(mobile);
				userTemp.setCreateTime(new Date());
				userDao.save(userTemp);
				Map<String, Object> map = tokenService.createToken(userTemp.getUserId(),"YH");
				map.put("firstLogin","1");
				return map;
			}
			user.setFirstLogin(false); //不是第一次登录了
			userDao.update(user);
			Map<String, Object> map = tokenService.createToken(user.getUserId(),"YH");
			map.put("firstLogin","0");
			return map;
		}
		Map<String, Object> map  = driverTokenService.createToken(driver.getId(),"SJ");
		map.put("firstLogin","0");
		return map;
	}

	@Override
	@Transactional
	public void cancelPsOrder(PsOrderEntity psOrder) {
		psOrder.setOrderStatus("3"); //订单状态改为已取消(用户)
		psOrderDao.update(psOrder);

		if (psOrder.getDriverId() != null) {	//订单已有司机接了
			SjDriverEntity driver = driverDao.queryObject(psOrder.getDriverId());
			driver.setGaoId(null);
			driver.setDriveStatus("0");
			driverDao.update(driver);

			//推送给司机，订单已被用户取消了
			try {
				QmSendPush.sendOrderCanceledToDriver(driver.getRegistrationId(),psOrder);
			} catch (Exception e) {
				throw new RRException("极光推送发生异常",-2);
			}

		}

	}

	@Override
	@Transactional
	public void selectCashPay(PsOrderEntity psOrder) {
		psOrder.setPayType("cash");
		psOrderDao.update(psOrder);

		SjDriverEntity driver = driverDao.queryObject(psOrder.getDriverId());
		//推送给司机，用户选择了现金支付方式
		try {
			QmSendPush.sendPsOrderCashPayToDriver(driver.getRegistrationId(),psOrder);
		} catch (Exception e) {
			throw new RRException("极光推送发生异常",-2);
		}


	}

	@Override
	@Transactional
	public void deleteFrequentlyRoute(Long routeId) {
		userFrequentlyRouteDao.delete(routeId);
		userFrequentlyRouteSectionDao.deleteByRouteId(routeId);
	}

	@Override
	public Map<String, Object> queryMineInfo(Long userId) {
		return userDao.queryMineInfo(userId);
	}

	@Override
	public void getCouponById(UserEntity user, Long couponid) {
		if (userCouponsService.isUserHaveCoupon(user,couponid)) { //若已经拥有这个
			UserCouponsEntity userCoupon = userCouponsService.queryObjectByUserIdAndCouponId(user.getUserId(),couponid);
			userCoupon.setCount(userCoupon.getCount() + 1); //将优惠券多加一张
			return ;
		}
		//没领过优惠券就新增一条数据
		PsCouponEntity psCouponEntity = psCouponService.queryObject(couponid);
		UserCouponsEntity userCouponsEntity = new UserCouponsEntity();
		userCouponsEntity.setPsCouponId(couponid);
		userCouponsEntity.setUserId(user.getUserId());
		userCouponsEntity.setStartTime(psCouponEntity.getStartTime());
		userCouponsEntity.setEndTime(psCouponEntity.getEndTime());
		userCouponsEntity.setStatus(1); //未使用
		userCouponsEntity.setCount(1);
		userCouponsService.save(userCouponsEntity);

	}


}
